<script setup>
	import { computed, ref, watch } from 'vue'
	import { DeleteOutlined, PlusOutlined, SettingOutlined } from '@ant-design/icons-vue'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'

	const emit = defineEmits(['change'])
	const store = useApiDatasetStore()

	// 参数表单数据
	const parameterList = ref([])
	const showSystemVariables = ref(false)

	// 支持的系统变量
	const systemVariables = [
		{ label: '当前用户ID', value: '${current_user_id}', description: '当前登录用户的ID' },
		{ label: '当前用户名', value: '${current_user_name}', description: '当前登录用户的用户名' },
		{ label: '当前用户部门ID', value: '${current_user_dept_id}', description: '当前登录用户的部门ID' },
		{ label: '当前用户部门名称', value: '${current_user_dept_name}', description: '当前登录用户的部门名称' },
		{ label: '当前日期', value: '${current_date}', description: '当前日期 (YYYY-MM-DD)' },
		{ label: '当前时间', value: '${current_datetime}', description: '当前日期时间 (YYYY-MM-DD HH:mm:ss)' },
		{ label: '当前时间戳', value: '${current_timestamp}', description: '当前时间戳 (毫秒)' }
	]

	// 当前选中的API信息
	const selectedApiInfo = computed(() => {
		return store.selectedApiInfo
	})

	// 初始化参数列表
	const initParameterList = () => {
		const apiParams = store.formData.itemConfig.apiParams || {}
		parameterList.value = Object.entries(apiParams).map(([key, value]) => ({
			id: Date.now() + Math.random(),
			name: key,
			value: value,
			enabled: true,
			description: ''
		}))

		// 如果没有参数且API有定义参数，则自动添加
		if (parameterList.value.length === 0 && selectedApiInfo.value?.parameters) {
			selectedApiInfo.value.parameters.forEach((param) => {
				parameterList.value.push({
					id: Date.now() + Math.random(),
					name: param.name,
					value: param.required ? '' : param.defaultValue || '',
					enabled: true,
					required: param.required,
					description: param.description || ''
				})
			})
		}
	}

	// 添加参数
	const addParameter = () => {
		parameterList.value.push({
			id: Date.now() + Math.random(),
			name: '',
			value: '',
			enabled: true,
			description: ''
		})
	}

	// 删除参数
	const removeParameter = (index) => {
		parameterList.value.splice(index, 1)
		updateApiParams()
	}

	// 更新API参数
	const updateApiParams = () => {
		const apiParams = {}
		parameterList.value.forEach((param) => {
			if (param.name && param.name.trim() && param.enabled) {
				apiParams[param.name.trim()] = param.value
			}
		})
		store.setApiParams(apiParams)
		emit('change')
	}

	// 插入系统变量
	const insertSystemVariable = (variable, paramIndex) => {
		if (parameterList.value[paramIndex]) {
			parameterList.value[paramIndex].value = variable.value
			updateApiParams()
		}
	}

	// 快速插入系统变量到新参数
	const quickInsertVariable = (variable) => {
		parameterList.value.push({
			id: Date.now() + Math.random(),
			name: variable.label.replace(/当前|ID|名称/g, '').toLowerCase(),
			value: variable.value,
			enabled: true,
			description: variable.description
		})
		updateApiParams()
	}

	// 监听API选择变化
	watch(
		() => store.formData.itemConfig.apiPath,
		() => {
			initParameterList()
		},
		{ immediate: true }
	)

	// 监听参数变化
	watch(
		parameterList,
		() => {
			updateApiParams()
		},
		{ deep: true }
	)
</script>

<template>
	<div class="api-debug-parameter-form">
		<!-- 参数列表 -->
		<div class="parameter-list">
			<div
				v-for="(param, index) in parameterList"
				:key="param.id"
				:class="{ disabled: !param.enabled }"
				class="parameter-item"
			>
				<div class="param-checkbox">
					<a-checkbox v-model:checked="param.enabled" @change="updateApiParams" />
				</div>
				<div class="param-name">
					<a-input v-model:value="param.name" placeholder="参数名" size="small" @change="updateApiParams" />
				</div>
				<div class="param-value">
					<a-input v-model:value="param.value" placeholder="参数值" size="small" @change="updateApiParams">
						<template #suffix>
							<a-dropdown v-if="systemVariables.length > 0" placement="bottomRight" trigger="click">
								<a-button size="small" type="text">
									<setting-outlined />
								</a-button>
								<template #overlay>
									<a-menu>
										<a-menu-item
											v-for="variable in systemVariables"
											:key="variable.value"
											@click="insertSystemVariable(variable, index)"
										>
											<div class="variable-menu-item">
												<div class="variable-label">{{ variable.label }}</div>
												<div class="variable-value">{{ variable.value }}</div>
											</div>
										</a-menu-item>
									</a-menu>
								</template>
							</a-dropdown>
						</template>
					</a-input>
				</div>
				<div class="param-actions">
					<a-button danger size="small" type="text" @click="removeParameter(index)">
						<delete-outlined />
					</a-button>
				</div>
			</div>

			<!-- 添加新参数 -->
			<div class="add-parameter">
				<a-button block size="small" type="dashed" @click="addParameter">
					<plus-outlined />
					添加参数
				</a-button>
			</div>
		</div>

		<!-- 系统变量快捷插入 -->
		<div v-if="systemVariables.length > 0" class="system-variables">
			<div class="variables-header">
				<span class="variables-title">系统变量</span>
				<a-button size="small" type="text" @click="showSystemVariables = !showSystemVariables">
					{{ showSystemVariables ? '收起' : '展开' }}
				</a-button>
			</div>
			<div v-show="showSystemVariables" class="variables-content">
				<div class="variables-grid">
					<div
						v-for="variable in systemVariables"
						:key="variable.value"
						class="variable-card"
						@click="quickInsertVariable(variable)"
					>
						<div class="variable-name">{{ variable.label }}</div>
						<div class="variable-code">{{ variable.value }}</div>
					</div>
				</div>
			</div>
		</div>

		<!-- API参数要求提示 -->
		<div v-if="selectedApiInfo?.parameters?.length > 0" class="api-params-info">
			<div class="info-title">API参数要求</div>
			<div class="info-list">
				<div v-for="param in selectedApiInfo.parameters" :key="param.name" class="info-item">
					<span class="param-name">{{ param.name }}</span>
					<span class="param-type">{{ param.type }}</span>
					<span v-if="param.required" class="param-required">必填</span>
					<span v-if="param.description" class="param-desc">{{ param.description }}</span>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.api-debug-parameter-form {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.parameter-list {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.parameter-item {
		display: grid;
		grid-template-columns: 40px 1fr 2fr 40px;
		gap: 8px;
		align-items: center;
		padding: 8px;
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		background: #fff;
		transition: all 0.2s ease;
	}

	.parameter-item:hover {
		border-color: #d9d9d9;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
	}

	.parameter-item.disabled {
		opacity: 0.5;
		background: #f9f9f9;
	}

	.param-checkbox {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.param-name,
	.param-value {
		display: flex;
		align-items: center;
	}

	.param-actions {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.add-parameter {
		margin-top: 8px;
	}

	.system-variables {
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		overflow: hidden;
	}

	.variables-header {
		padding: 12px 16px;
		background: #fafafa;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.variables-title {
		font-weight: 600;
		color: #262626;
		font-size: 14px;
	}

	.variables-content {
		padding: 16px;
	}

	.variables-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
		gap: 8px;
	}

	.variable-card {
		padding: 8px 12px;
		border: 1px solid #e8e8e8;
		border-radius: 4px;
		cursor: pointer;
		transition: all 0.2s ease;
		background: #fff;
	}

	.variable-card:hover {
		border-color: #1890ff;
		background: #f6f8ff;
	}

	.variable-name {
		font-size: 12px;
		color: #262626;
		font-weight: 500;
	}

	.variable-code {
		font-size: 11px;
		color: #8c8c8c;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		margin-top: 2px;
	}

	.variable-menu-item {
		display: flex;
		flex-direction: column;
		gap: 2px;
	}

	.variable-label {
		font-size: 12px;
		color: #262626;
	}

	.variable-value {
		font-size: 11px;
		color: #8c8c8c;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
	}

	.api-params-info {
		padding: 12px;
		background: #f6f8ff;
		border: 1px solid #e6f0ff;
		border-radius: 6px;
	}

	.info-title {
		font-size: 12px;
		font-weight: 600;
		color: #1890ff;
		margin-bottom: 8px;
	}

	.info-list {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.info-item {
		display: flex;
		align-items: center;
		gap: 8px;
		font-size: 12px;
	}

	.param-name {
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-weight: 600;
		color: #262626;
	}

	.param-type {
		color: #8c8c8c;
		font-style: italic;
	}

	.param-required {
		color: #ff4d4f;
		font-weight: bold;
		font-size: 11px;
	}

	.param-desc {
		color: #8c8c8c;
		flex: 1;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.parameter-item {
			grid-template-columns: 30px 1fr 30px;
			gap: 4px;
		}

		.param-name {
			grid-column: 1 / -1;
			margin-top: 4px;
		}

		.variables-grid {
			grid-template-columns: 1fr;
		}
	}
</style>
